package com.dxj1992.utils;

import com.dxj1992.entity.AdminPermissions;

import java.util.ArrayList;
import java.util.List;

public class Tree {

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param adminPermissions
     * @param parentId
     * @return
     */
    public static List<AdminPermissions> getMenu(List<AdminPermissions> adminPermissions, Integer parentId) {
        List<AdminPermissions> returnList = new ArrayList<>();
        for (AdminPermissions adminPermission : adminPermissions) {
            if (adminPermission.getParentId() == parentId) {
                recursionFn(adminPermissions, adminPermission);
                returnList.add(adminPermission);
            }
        }
        return returnList;
    }

    /**
     * 递归
     */
    private static void recursionFn(List<AdminPermissions> adminPermissions, AdminPermissions p) {
        List<AdminPermissions> child = getChild(adminPermissions, p);
        p.setChildren(child);
        for (AdminPermissions permissions : child) {
            if (hasChild(adminPermissions, permissions)) {
                recursionFn(adminPermissions, permissions);
            }
        }
    }

    /**
     * 得到子节点列表
     *
     * @param list
     * @param p
     */
    public static List<AdminPermissions> getChild(List<AdminPermissions> list, AdminPermissions p) {
        List<AdminPermissions> clist = new ArrayList<>();
        for (AdminPermissions adminPermission : list) {
            if (adminPermission.getParentId() == p.getId()) {
                clist.add(adminPermission);
            }
        }
        return clist;
    }


    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<AdminPermissions> list, AdminPermissions t) {
        return getChild(list, t).size() > 0;
    }

}
